<?php

namespace App\Repositories;


use App\Models\Goods;
use App\Interfaces\SolrService;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Solarium\Client;
use GuzzleHttp\Client as HttpClient;

class SolrRepository implements SolrService{

    protected $config;

    protected $client;

    public function __construct(){
        $this->config = config('solr');
        $this->client = 11;//new Client($this->config);
    }

    public function suggest($keyword,$limit=15){

        //return collect(['keyword'=>7,'count'=>'haha']);
    /*    $client  = $this->client;

        $query = $client->createSelect();

        $facetSet = $query->getFacetSet();

        $facetSet->createFacetField('search_keywords')
            ->setField('search_keywords')
            ->setPrefix($keyword)
            ->setLimit($limit)
            //->setSort('true(index,lex)')
            ->setMinCount(1);
            ;
        $resultset = $client->select($query);

        $facet = $resultset->getFacetSet()->getFacet('search_keywords');

        $facet =  collect($facet->getValues());*/

        $keywords = collect();
        $keywords->push(['keyword'=>'hehe','count'=>1]);
       /* foreach ($facet as $k=>$v){

            $keywords = $keywords->push(['keyword'=>$k,'count'=>$v]);
        }*/
        return $keywords;


    }


    public function update(Goods $goods){
     return true;
        $client = $this->client;
        $update = $client->createUpdate();
        $doc = $update->createDocument();
        //dd($goods);
        //字段列表
        $doc->goods_id = $goods->goods_id;
        $doc->goods_sn = $goods->goods_sn;
        $doc->goods_name = $goods->goods_name;
        $doc->goods_pet_name = $goods->goods_pet_name;
        $doc->goods_desc = $goods->goods_desc;
        $doc->keywords = $goods->keywords;
        $doc->search_keywords = $goods->search_keywords;
        //$doc->is_on_sale = $goods->is_on_sale;
        $doc->cat_id = $goods->cat_id;
        $doc->brand_id = $goods->brand_id;
        $doc->goods_number = $goods->goods_number;
        $doc->shop_price = $goods->shop_price;
        $doc->shop_id = $goods->shop_id;
        $doc->sales_num = $goods->sales_num;
        $doc->updated_at = gmDate("Y-m-d\TH:i:s.z\Z",strtotime($goods->updated_at));
        $update->addDocument($doc);
        $update->addCommit();

        return $result = $client->update($update);

    }

    public function delete($goods_id){
        return true;
        $client = $this->client;
        $update = $client->createUpdate();

        $update->addDeleteQuery('goods_id:'.$goods_id);
        $update->addCommit();
        return $result = $client->update($update);
    }

    //public function search($keyword='*',$cat_id='*',$brand_id='*',$is_on_sale='*',$page=1,$pageSize=15,$orderType=''){
    public function search($keyword='*',$cat_id='*',$brand_id='*',$has_stock=false,$page=1,$pageSize=15,$orderType='',$shop_id='*'){


        $client = $this->client;

        //设置搜索过滤
        $query = $client->createSelect();

        $keyword = str_replace(' ','',$keyword);
        $keyword = preg_replace('/(\+|-|&|\||!|||\{|}|\[|]|\^|"|~|\*|\?|:|;|~|\/)/','',$keyword);

        if ($keyword=='') $keyword='*';

        $queryStr = 'goods_name:{{keywrod}} OR keywords:{{keywrod}} OR search_keywords:{{keywrod}} OR goods_desc:{{keywrod}}';

        $queryStr = str_replace('{{keywrod}}',$keyword,$queryStr);

        //关键词搜索
        $query->setQuery($queryStr);

        //分页
        $page = max($page, 1);
        $query->setStart(ceil($page-1)*$pageSize);
        $query->setRows($pageSize);


        //facet
        $facetSet = $query->getFacetSet();
        $facetSet->setMinCount(1);
        $facetSet->createFacetField('brand_id')->setField('brand_id')->addExclude('brand_id_tag');
        //$facetSet->createFacetField('shop_id')->setField('shop_id');
        //$facetSet->createFacetField('cat_id')->setField('cat_id');
        //$facetSet->createFacetField('shop_price')->setField('shop_price');

        //筛选查询


//        if ($cat_id!='*'&&intval($cat_id)!=0) {
//            $query->createFilterQuery()->addTag('cat_id_tag')->setQuery(sprintf('cat_id:%s', $cat_id));
//        }

        if ($brand_id!='*'&&intval($brand_id)!=0) {
            $query->createFilterQuery('brand_id')->addTag('brand_id_tag')->setQuery(sprintf('brand_id:%s', $brand_id));
        }
        //筛选店铺
        if ($shop_id!='*'&&intval($shop_id)!=0) {
            $query->createFilterQuery('shop_id')->addTag('shop_id_tag')->setQuery(sprintf('shop_id:%s', $shop_id));
        }


        //筛选库存
        if($has_stock){
            $query->createFilterQuery('goods_number')->setQuery(sprintf('goods_number:%s','[1 TO *]'));
        }else{
            $query->createFilterQuery('goods_number')->setQuery(sprintf('goods_number:%s','[0 TO *]'));
        }


        //排序
        //销量排序 类型: sale_desc|sale_asc
        if ($orderType=='sale_desc'){
            $query->addSort('sales_num', 'desc');
        }elseif($orderType=='sale_asc'){
            $query->addSort('sales_num', 'asc');
        }

        //价格排序 类型:price_desc|price_asc
        if ($orderType=='price_desc'){
            $query->addSort('shop_price', 'desc');
        }elseif($orderType=='price_asc'){
            $query->addSort('shop_price', 'asc');
        }

        //$query->addSort('updated_at', 'desc');

        $resultset = $client->select($query);

        $total = $resultset->getNumFound();

        $facetSet = $resultset->getFacetSet();

        $docs  = $resultset->getDocuments();

        $page = $page ?: Paginator::resolveCurrentPage('page');

        $paginate =  new LengthAwarePaginator($docs, $total, $pageSize, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);

        $data['facetSet'] = $facetSet;
        $data['paginate'] = $paginate;
//dd($data);
        return $data;


    }


    //public function category(Array $cat_ids,$cat_id,$brand_id='*',$is_on_sale='*',$page=1,$pageSize=15,$orderType=''){
    public function category(Array $cat_ids,$cat_id,$brand_id='*',$has_stock=false,$page=1,$pageSize=15,$orderType=''){
            return null;
        $client = $this->client;

        //设置搜索过滤
        $query = $client->createSelect();

        foreach ($cat_ids as $k=>$v){
            $cat_ids[$k] = 'cat_id:'.$v;
        }

        $queryStr = (implode(' OR ',$cat_ids));

        //关键词搜索
        $query->setQuery($queryStr);

        //分页
        $page = max($page, 1);
        $query->setStart(ceil($page-1)*$pageSize);
        $query->setRows($pageSize);


        //facet
        $facetSet = $query->getFacetSet();
        $facetSet->setMinCount(1);
//        $facetSet->createFacetField('brand_id')->setField('brand_id')->addExclude('brand_id_tag');
        $facetSet->createFacetField('cat_id')->setField('cat_id')->addExclude('cat_id_tag');

        //筛选查询


        if ($cat_id!='*'&&intval($cat_id)!=0) {
            $query->createFilterQuery('cat_id')->addTag('cat_id_tag')->setQuery(sprintf('cat_id:%s', $cat_id));
        }

//        if ($brand_id!='*'&&intval($brand_id)!=0) {
//            $query->createFilterQuery('brand_id')->addTag('brand_id_tag')->setQuery(sprintf('brand_id:%s', $brand_id));
//        }


        if($has_stock){
            $query->createFilterQuery('goods_number')->setQuery(sprintf('goods_number:%s','[1 TO *]'));
        }else{
            $query->createFilterQuery('goods_number')->setQuery(sprintf('goods_number:%s','[0 TO *]'));
        }


        //排序

        //销量排序 类型: sale_desc|sale_asc
        if ($orderType=='sale_desc'){
            $query->addSort('sales_num', 'desc');
        }elseif($orderType=='sale_asc'){
            $query->addSort('sales_num', 'asc');
        }

        //价格排序 类型:price_desc|price_asc
        if ($orderType=='price_desc'){
            $query->addSort('shop_price', 'desc');
        }elseif($orderType=='price_asc'){
            $query->addSort('shop_price', 'asc');
        }
        $query->addSort('sort_order', 'desc');

        $query->addSort('created_at', 'desc');

        $resultset = $client->select($query);

//dd($cat_id);
        $total = $resultset->getNumFound();

        $facetSet = $resultset->getFacetSet();

        $docs  = $resultset->getDocuments();

        $page = $page ?: Paginator::resolveCurrentPage('page');

        $paginate =  new LengthAwarePaginator($docs, $total, $pageSize, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);

        $data['facetSet'] = $facetSet;
        $data['paginate'] = $paginate;

        return $data;


    }

    public function dataImport(){
            return null;
        //$url = $this->client->getEndpoint()->getBaseUri().'data-import?command=delta-import&indent=true&wt=json';
        $url = $this->client->getEndpoint()->getBaseUri().'data-import?command=full-import';
        //dd($url);
        return (new HttpClient)->get($url)->getReasonPhrase();

    }


}